﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class EventProcess
{ 
    //注册事件(使用时要注意，在类对象不用时一定要清事件，不然gc不掉)
    public static void Rigester(string eventName,Action<object> action)
    {
        if(!string.IsNullOrEmpty(eventName) && action != null)
        {
            HashSet<Action<object>> actionList = null;
            if (!m_eventDic.ContainsKey(eventName))
            {
                actionList = new HashSet<Action<object>>();
                m_eventDic[eventName] = actionList;
            }
            else
            {
                actionList = m_eventDic[eventName];
            }
            if(!actionList.Contains(action))
            {
                actionList.Add(action);
            }
        }
    }

    //派发事件
    public static void Dispatch(string eventName,object param = null)
    {
        if(m_eventDic.ContainsKey(eventName) && m_eventDic[eventName] != null)
        {
            HashSet<Action<object>>.Enumerator actionlist = m_eventDic[eventName].GetEnumerator();
            while (actionlist.MoveNext())
            {
                actionlist.Current(param);
            }
        }
    }

    //清理
    public static void Destroy()
    {
        m_eventDic.Clear();
    }

    private static Dictionary<string, HashSet<Action<object>>> m_eventDic = new Dictionary<string, HashSet<Action<object>>>();
}
